import xlrd,os
def readExcelDataByName(fileName, sheetName):
    table = None
    errorMsg = None
    try:
        data = xlrd.open_workbook(fileName)
        table = data.sheet_by_name(sheetName)
    except Exception as err:
        errorMsg = str(err)
    return table, errorMsg
def readExcelDataByIndex(fileName, sheetIndex):
    table = None
    errorMsg = ""
    try:
        data = xlrd.open_workbook(fileName)
        table = data.sheet_by_index(sheetIndex)
    except Exception as err:
        errorMsg = str(err)
    return table, errorMsg
def getColumnIndex(table, columnName):
    columnIndex = None
    for i in range(table.ncols):
        if(table.cell_value(0, i) == columnName):
            columnIndex = i
            break
    return columnIndex
#获取指定目录下的目录
def get_dirs_from_dir(dirpath):
    all_equiplist = list()
    for fdir in os.listdir(dirpath):
        newPath = os.path.join(dirpath,fdir)
        if os.path.isdir(newPath):
            if fdir == '__pycache__':
                continue
            all_equiplist.append(fdir)
    return all_equiplist
#获取指定目录下的文件
def get_files_from_dir(dirpath):
    files = list()
    for file in os.listdir(dirpath):

        filepath = os.path.join(dirpath, file)
        if os.path.isfile(filepath):
            if os.path.splitext(filepath)[1] == '.xlsx' or os.path.splitext(filepath)[1] == '.xls':
                files.append(filepath)
    return files
#获取一组Excel文件中所有的tag
def get_all_tags_from_files(files):
    tags = list()
    for file in files:
        tag_table = readExcelDataByName(file, r"Sheet1")[0]
        if tag_table:
            if tag_table.nrows <=0 :
                continue
            for i in range(1, tag_table.nrows):
                tag = tag_table.cell_value(i, getColumnIndex(tag_table, r'TagID'))
                tag = str(tag).strip()
                if tag is None or tag =='' or tag.startswith("#"):
                    continue
                tags.append(tag)
    return tags

def add_prefix(tags,prefix):
    newTags = list()
    for tag in tags:
        newTags.append(prefix+tag)

    return newTags